import pathlib

import qasync
from PySide6 import QtCore, QtGui

from PySide6.QtWidgets import QFrame

from src.ui.ui.ListeningFileList_ui import Ui_Form

from src.service import save_node_service


class ListeningFileList(QFrame, Ui_Form):
    item_click_signal = QtCore.Signal(str)

    def __init__(self, parent):
        super(ListeningFileList, self).__init__(parent=parent)
        self.setupUi(self)

        self.list_model = QtGui.QStandardItemModel()
        self.listView.setModel(self.list_model)

        self.listView.clicked.connect(lambda x: self.on_item_click(x))

    @qasync.asyncSlot()
    async def refresh(self):
        listening_files = save_node_service.listening_files()
        for item, index in zip(listening_files, range(listening_files.__len__())):
            standard_item = QtGui.QStandardItem(pathlib.Path(item[0]).name)
            standard_item.setData(item[0], 1)
            self.list_model.setItem(index, 0, standard_item)

    def on_item_click(self, index: QtCore.QModelIndex):
        item = self.list_model.itemFromIndex(index)
        self.item_click_signal.emit(item.data(1))
